<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\Opus as OpusModel;

/**
 * 首页接口.
 */
class Opus extends Api
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];

    /**
     * 首页.
     */
    public function index()
    {
        $this->success('请求成功');
    }

    /**
     * 获取作品证书编码
     */
    public function getNO()
    {
        $uid = $this->auth->id;
        $opus = OpusModel::get(['user_id' => $uid,'image'=>'']);
        if (!$opus) {
            $opus = new OpusModel;
            $opus->user_id         = $uid;
            $opus->image           = '';
            $opus->certificateNo   = '';
            if (!$opus->save()){
                $this->error('生成证书编码失败');
            }
            $opus->certificateNo = 'NO.'.str_pad($opus->id,8,"0",STR_PAD_LEFT);
            if (!$opus->save()){
                $this->error('生成证书编码失败！');
            }
        }

        $this->success('获取成功',['opus_id'=>$opus->id,'certificateNo'=>$opus->certificateNo]);
    }

    /**
     * 用户作品上传
     */
    public function add()
    {
        $img = $this->request->request('img');
        $image = $this->request->request('image');
        $certificateNo = $this->request->request('certificateNo');
        $channel = $this->request->request('channel');
        if (empty($img)) {
            $this->error('img不能为空');
        }
        if (empty($image)) {
            $this->error('image不能为空');
        }
        if (empty($certificateNo)) {
            $this->error('certificateNo不能为空');
        }
        $uid = $this->auth->id;
        $opus = OpusModel::get(['user_id' => $uid,'certificateNo' => $certificateNo]);
        if (!$opus) {
            $this->error('找不到证书记录');
        }
        if (!empty($opus->image)) {
            $this->error('不能重复上传证书');
        }
        $opus->img     = $img;
        $opus->image   = $image;
        $opus->channel = $channel;

        if ($opus->save()){
            $this->success('上传成功',$opus);
        }

        $this->error('请求失败');
    }

    /**
     * 获取作品
     */
    public function getOpus()
    {
        $params = $this->request->request();

        $query = OpusModel::alias('o')->join('user u','u.id=o.user_id','left')->field('o.*,u.nickname,u.email');
        if (!empty($params['id'])) {
            $query->where(['id'=>$params['id']]);
        }
        if (!empty($params['user_id'])) {
            $query->where(['user_id'=>$params['user_id']]);
        }
        $query->order('id','DESC');
        if (!empty($params['page'])) {
            $limit = $params['limit']?:10;
            $offset = ($params['page']-1)*$limit;
            $query->limit($offset, $limit);
        }
        $opus = $query->fetchSql(false)->select();
        // $opus = $query->select();

        $this->success('请求成功',$opus);
    }
}
